package com.useeinfo.demo.open.dashboard;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.demo.common.config.ConstantKeyFilePath;
import com.useeinfo.demo.modules.logging.biz.AttendanceInfoBiz;
import com.useeinfo.demo.modules.logging.biz.FeedBackInfoBiz;
import com.useeinfo.demo.modules.logging.biz.FeedBackTypeBiz;
import com.useeinfo.demo.modules.logging.entity.AttendanceInfo;
import com.useeinfo.demo.modules.logging.entity.FeedBackInfo;
import com.useeinfo.demo.modules.logging.entity.FeedBackType;
import com.useeinfo.framework.extend.action.BaseAction;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import dingding.Env;
import dingding.OApiException;
import dingding.auth.AuthHelper;
import dingding.user.User;
import dingding.user.UserHelper;
import dingding.utils.WeChatSign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by gjj
 */
@Controller
@RequestMapping("/access")
public class AccessAction extends BaseAction {

    @Autowired
    private FeedBackTypeBiz feedBackTypeBiz;

    @Autowired
    private AttendanceInfoBiz attendanceInfoBiz;

    @Autowired
    private FeedBackInfoBiz feedBackInfoBiz;

    /**
     * 获取首页需要的参数
     */
    @RequestMapping("/home")
    public ModelAndView HomePage() {

        ModelAndView modelAndView = new ModelAndView();
        try {
            JSONObject jsonObject = this.getTokenData(Env.HOME_PAGE_URL);
            modelAndView.addObject("agentId", Env.AGENT_ID);
            modelAndView.addObject("corpId", Env.CORP_ID);
            modelAndView.addObject("timeStamp", String.valueOf(jsonObject.get("timeStamp")));
            modelAndView.addObject("nonceStr", Env.NONCESTR);
            modelAndView.addObject("signature", String.valueOf(jsonObject.get("signature")));
            modelAndView.addObject("accessToken", String.valueOf(jsonObject.get("accessToken")));
            modelAndView.setViewName("resources/dd/homePage");
            return modelAndView;
        } catch (OApiException e) {
            e.printStackTrace();
            return modelAndView;
        }
    }


    /**
     * 进店签到页面初始化钉钉参数
     */
    @RequestMapping("/in")
    public ModelAndView intoStore() {

        ModelAndView modelAndView = new ModelAndView();
        try {
            JSONObject jsonObject = this.getTokenData(Env.INTO_STORE_URL);
            modelAndView.addObject("agentId", Env.AGENT_ID);
            modelAndView.addObject("corpId", Env.CORP_ID);
            modelAndView.addObject("timeStamp", String.valueOf(jsonObject.get("timeStamp")));
            modelAndView.addObject("nonceStr", Env.NONCESTR);
            modelAndView.addObject("signature", String.valueOf(jsonObject.get("signature")));
            modelAndView.addObject("accessToken", String.valueOf(jsonObject.get("accessToken")));
            modelAndView.setViewName("resources/dd/intoStore");
            return modelAndView;
        } catch (OApiException e) {
            e.printStackTrace();
            return modelAndView;
        }
    }
//

    /**
     * 离店签到页面初始化钉钉参数
     */
    @RequestMapping("/out")
    public ModelAndView outStore() {

        ModelAndView modelAndView = new ModelAndView();
        try {
            JSONObject jsonObject = this.getTokenData(Env.OUT_STORE_URL);
            modelAndView.addObject("agentId", Env.AGENT_ID);
            modelAndView.addObject("corpId", Env.CORP_ID);
            modelAndView.addObject("timeStamp", String.valueOf(jsonObject.get("timeStamp")));
            modelAndView.addObject("nonceStr", Env.NONCESTR);
            modelAndView.addObject("signature", String.valueOf(jsonObject.get("signature")));
            modelAndView.addObject("accessToken", String.valueOf(jsonObject.get("accessToken")));
            modelAndView.setViewName("resources/dd/outStore");
            return modelAndView;
        } catch (OApiException e) {
            e.printStackTrace();
            return modelAndView;
        }
    }

    /**
     * 获取登录用户信息
     */
    @RequestMapping("/user")
    @ResponseBody
    public JSONObject GetUserInfo(@RequestParam(value = "accessToken", required = false) String accessToken,
                                  @RequestParam(value = "code", required = false) String code) throws OApiException {

        logger.info("成功获取access token: " + accessToken);
        User user = UserHelper.getUser(accessToken, UserHelper.getUserInfo(accessToken, code).getString("userid"));
        String userJson = JSON.toJSONString(user);
        System.out.println("userjson:" + userJson);
        JSONObject jsonObject = JSON.parseObject(userJson);
        return jsonObject;
    }

    public JSONObject getTokenData(String url) throws OApiException {

        JSONObject jsonObject = new JSONObject();

        // 获取access token
        String accessToken = AuthHelper.getAccessToken();
        logger.info("成功获取access token: " + accessToken);
        jsonObject.put("accessToken", accessToken);
        // 获取jsapi ticket
        String ticket = AuthHelper.getJsapiTicket(accessToken);
        logger.info("成功获取jsapi ticket: " + ticket);
        jsonObject.put("ticket", ticket);

        // 获取签名
        String nonceStr = "nonceStr";
        long timeStamp = System.currentTimeMillis();
        String signature = AuthHelper.sign(ticket, Env.NONCESTR, timeStamp, url);
        logger.info("成功签名: " + signature);
        jsonObject.put("signature", signature);
        jsonObject.put("timeStamp", timeStamp);
        return jsonObject;
    }

    public JSONObject getUserInfo(String accessToken, String code) throws OApiException {
        JSONObject jsonObject = new JSONObject();
        logger.info("成功获取access token: " + accessToken);
        User user = UserHelper.getUser(accessToken, UserHelper.getUserInfo(accessToken, code).getString("userid"));
        String userJson = JSON.toJSONString(user);
        System.out.println("userjson:" + userJson);
        jsonObject = JSON.parseObject(userJson);
        return jsonObject;
    }

    /**
     * 获取当前登录用户的签到数据列表
     */
    @RequestMapping("/getList")
    @ResponseBody
    public JSONObject getPositionListJSON(@RequestParam(value = "accessToken", required = false) String accessToken,
                                          @RequestParam(value = "code", required = false) String code) {
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject userObj = this.getUserInfo(accessToken, code);
            jsonObject.put("userInfo", userObj);
            String userName = userObj.getString("name");
            if (StringUtils.isBlank(userName)) {
                jsonObject.put("code", "0");
                jsonObject.put("msg", "未获取到当前登录者信息");
                return jsonObject;
            }
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("userName", userName);
            queryParam.getSqlMap().put("dutyDate", DateTimeUtils.formatDateToString(new Date()));
            JSONArray jsonArray = new JSONArray();
            List<AttendanceInfo> attendanceInfoList = attendanceInfoBiz.findList(queryParam);
            for (AttendanceInfo attendanceInfo : attendanceInfoList) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("shopName", attendanceInfo.getShopName());
                if (attendanceInfo.getInDutyTime() != null)
                    jsonObject1.put("inDutyTime", DateTimeUtils.getHourOfDay(attendanceInfo.getInDutyTime()) + ":" + DateTimeUtils.getMinute(attendanceInfo.getInDutyTime()));
                else
                    jsonObject1.put("inDutyTime", "");
                if (attendanceInfo.getOutDutyTime() != null)
                    jsonObject1.put("outDutyTime", DateTimeUtils.getHourOfDay(attendanceInfo.getOutDutyTime()) + ":" + DateTimeUtils.getMinute(attendanceInfo.getOutDutyTime()));
                else
                    jsonObject1.put("outDutyTime", "");
                jsonObject1.put("inDutyPhoto", attendanceInfo.getInDutyPhoto());
                jsonObject1.put("outDutyPhoto", attendanceInfo.getOutDutyPhoto());
                jsonObject1.put("inLatitude", attendanceInfo.getInLatitude());
                jsonObject1.put("inLongitude", attendanceInfo.getInLongitude());
                jsonObject1.put("outLatitude", attendanceInfo.getOutLatitude());
                jsonObject1.put("outLongitude", attendanceInfo.getOutLongitude());
                jsonObject1.put("inExceptionId", attendanceInfo.getInExceptionId());
                jsonObject1.put("outExceptionId", attendanceInfo.getOutExceptionId());
                jsonArray.add(jsonObject1);
            }
            jsonObject.put("jsArray", jsonArray);
            jsonObject.put("code", "1");
            jsonObject.put("msg", "获取成功");
            return jsonObject;
        } catch (OApiException e) {
            jsonObject.put("code", "0");
            jsonObject.put("msg", "加载签到数据发生未知错误");
            return jsonObject;
        }
    }


    /**
     * 签到数据提交
     */
    @RequestMapping(value = "/attend/submit", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String reportAttendanceInfo(@RequestParam(value = "photo", required = false) String photo,
                                       @RequestParam(value = "longitude", required = false) String longitude,
                                       @RequestParam(value = "latitude", required = false) String latitude,
                                       @RequestParam(value = "userName", required = false) String userName,
                                       @RequestParam(value = "userTel", required = false) String userTel,
                                       @RequestParam(value = "store", required = false) String store,
                                       @RequestParam(value = "dutyType", required = false) String dutyTypeParam,
                                       HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(store)) {
            return "请输入门店名称";
        }

        List<AttendanceInfo> attendanceInfos = attendanceInfoBiz.findAttendance(userTel, store);
        if (dutyTypeParam.equals("in")) {
            if (!CollectionUtils.isEmpty(attendanceInfos)) {
                return "今日已签到过当前门店,无法重复提交";
            } else {
                String docPath = FileUtils.getContextRootPath(request) + ConstantKeyFilePath.ON_DUTY_PHOTO_DIR;
                String filePath = docPath + "/";
                filePath += new SimpleDateFormat("yyyyMMdd").format(new Date());
                String fileName = ConstantKeyFilePath.ON_DUTY_PHOTO_FIX + "_" + FileUtils.getFileNameByDateTime() + ".jpg";
                WeChatSign.download(photo, fileName, filePath);
                System.out.println(filePath + File.separator + fileName);
                AttendanceInfo attendanceInfo = new AttendanceInfo();
                attendanceInfo.setDutyDate(StringConverters.ToDateOnly(DateTimeUtils.formatDateToStringWithTime(new Date())));
                attendanceInfo.setInDutyTime(new Date());
                attendanceInfo.setInLatitude(latitude);
                attendanceInfo.setInLongitude(longitude);
                attendanceInfo.setUserName(userName);
                attendanceInfo.setShopName(store);
                attendanceInfo.setUserTel(userTel);
                attendanceInfo.setInDutyPhoto(filePath + File.separator + fileName);
                attendanceInfoBiz.addOrUpdate(attendanceInfo);
            }

        } else {
            if (CollectionUtils.isEmpty(attendanceInfos)) {
                return "请进店打卡";
            } else {
                String docPath = FileUtils.getContextRootPath(request) + ConstantKeyFilePath.OFF_DUTY_PHOTO_DIR;
                String filePath = docPath + "/";
                filePath += new SimpleDateFormat("yyyyMMdd").format(new Date());
                String fileName = ConstantKeyFilePath.OFF_DUTY_PHOTO_FIX + "_" + FileUtils.getFileNameByDateTime() + ".jpg";
                WeChatSign.download(photo, fileName, filePath);
                System.out.println(filePath + File.separator + fileName);
                AttendanceInfo attendanceInfo = attendanceInfos.get(0);
                attendanceInfo.setOutLatitude(latitude);
                attendanceInfo.setOutLongitude(longitude);
                attendanceInfo.setOutDutyPhoto(filePath + File.separator + fileName);
                attendanceInfoBiz.addOrUpdate(attendanceInfo);
            }
        }

        return "success";
    }

    /**
     * 问题反馈查询页面
     */
    @RequestMapping(value = "/feedback/query", produces = {"text/plain;charset=UTF-8"})
    public ModelAndView feedBack(@RequestParam(value = "exceptionId", required = false) String exceptionId,
                                 @RequestParam(value = "userName", required = false) String userName,
                                 @RequestParam(value = "userTel", required = false) String userTel,
                                 @RequestParam(value = "dutyType", required = false) String dutyTypeParam) {

        ModelAndView modelAndView = new ModelAndView();

        List<FeedBackType> feedBackTypeList = feedBackTypeBiz.findList();
        modelAndView.addObject("feedBackTypeList", feedBackTypeList);
        modelAndView.addObject("dutyType", dutyTypeParam);
        modelAndView.addObject("userName", userName);
        modelAndView.addObject("userTel", userTel);

        if (StringUtils.isNotBlank(exceptionId)) {
            modelAndView.addObject("exceptionId", exceptionId);
            FeedBackInfo feedBackInfo = feedBackInfoBiz.findModel(StringConverters.ToLong(exceptionId));
            modelAndView.addObject("describe", feedBackInfo.getDescribe());
            modelAndView.addObject("type", feedBackInfo.getFeedBackType());
            modelAndView.addObject("storeName", feedBackInfo.getStoreName());
        }
        modelAndView.setViewName("resources/dd/feedback");
        return modelAndView;
    }

    /**
     * 问题反馈提交
     */
    @RequestMapping(value = "/feedback/submit", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String feedback(@RequestParam(value = "userName", required = false) String userName,
                           @RequestParam(value = "userTel", required = false) String userTel,
                           @RequestParam(value = "feedbackType", required = false) String feedbackType,
                           @RequestParam(value = "dutyType", required = false) String dutyTypeParam,
                           @RequestParam(value = "exceptionId", required = false) String exceptionId,
                           FeedBackInfo feedBackInfo) throws Exception {

        if (StringUtils.isEmpty(feedBackInfo.getDescribe()))
            return "请填写问题描述";
        if (StringUtils.isEmpty(feedBackInfo.getStoreName()))
            return "请填写门店名称";
        if (StringUtils.isEmpty(feedbackType))
            return "请选择反馈类型";
        //根据异常ID获取反馈信息
        FeedBackInfo existFeedBackInfo = feedBackInfoBiz.findModel(StringConverters.ToLong(exceptionId));
        if (existFeedBackInfo == null) {
            //如果是空，则新增
            feedBackInfo.setFeedBackTime(new Date());
            feedBackInfo.setName(userName);
            feedBackInfo.setTel(userTel);
            feedBackInfo.setFeedBackType(feedbackType);
            feedBackInfoBiz.addOrUpdate(feedBackInfo);
            //同步到签到数据中，记录反馈ID
            List<AttendanceInfo> attendanceInfoList = attendanceInfoBiz.findAttendance(userTel, feedBackInfo.getStoreName());
            if (CollectionUtils.isEmpty(attendanceInfoList)) {
                AttendanceInfo attendanceInfo = new AttendanceInfo();
                attendanceInfo.setDutyDate(StringConverters.ToDateOnly(DateTimeUtils.formatDateToStringWithTime(new Date())));
                attendanceInfo.setUserName(userName);
                attendanceInfo.setShopName(feedBackInfo.getStoreName());
                attendanceInfo.setUserTel(userTel);
                if (dutyTypeParam.equals("in")) {
                    attendanceInfo.setInExceptionId(feedBackInfo.getId());
                } else {
                    attendanceInfo.setOutExceptionId(feedBackInfo.getId());
                }
                attendanceInfoBiz.addOrUpdate(attendanceInfo);
            } else {
                AttendanceInfo attendanceInfo = attendanceInfoList.get(0);
                if (dutyTypeParam.equals("in")) {
                    attendanceInfo.setInExceptionId(feedBackInfo.getId());
                } else {
                    attendanceInfo.setOutExceptionId(feedBackInfo.getId());
                }
                attendanceInfoBiz.addOrUpdate(attendanceInfo);
            }
        } else {
            //如果不为空，则更新
            existFeedBackInfo.setFeedBackTime(new Date());
            existFeedBackInfo.setFeedBackType(feedbackType);
            existFeedBackInfo.setDescribe(feedBackInfo.getDescribe());
            feedBackInfoBiz.addOrUpdate(existFeedBackInfo);
        }
        return "success";

    }
}
